package edu.whu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.whu.bean.Product;
import edu.whu.bean.Supplier;
import edu.whu.dao.ProductMapper;
import edu.whu.exception.ProductException;
import edu.whu.service.ProductService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class ProductServiceImpl implements ProductService {

    private final ProductMapper mapper;

    public ProductServiceImpl(ProductMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public int insert(Product product){
        return mapper.insert(product);
    }
    @Override
    public int save(Product product){
        Product p = mapper.selectById(product.getId());
        if(p == null){
            return mapper.insert(product);
        }
        else{
            return mapper.updateById(product);
        }
    }
    @Override
    public List<Product> select(String param, Object value){
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if("name".equalsIgnoreCase(param)){
            wrapper.eq(Product::getName, value);
        } else if ("price".equalsIgnoreCase(param)) {
            wrapper.eq(Product::getPrice,value);
        } else if ("count".equalsIgnoreCase(param)) {
            wrapper.eq(Product::getCount,value);
        } else if ("sales".equalsIgnoreCase(param)) {
            wrapper.eq(Product::getSales,value);
        } else {
            return new ArrayList<>();
        }
        return mapper.selectList(wrapper);
    }
    @Override
    public Product selectById(int id){
        return mapper.selectById(id);
    }

    @Override
    public List<Product> selectAll() {
        return mapper.selectList(new QueryWrapper<>());
    }
    @Override
    public int deleteById(int id) throws ProductException {
        try {
            return mapper.deleteById(id);
        }catch (Exception e){
            throw new ProductException("删除的商品不存在");
        }

    }
    @Override
    public List<Supplier> selectSupplier(int id){
        return mapper.selectSuppliers(id);
    }


    @Override
    public List<Product> selectCountGreater(int count) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.gt(Product::getCount,count);

        return mapper.selectList(wrapper);
    }

}
